package org.gd.hellomysql;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public abstract class ConnectionFactory {

    private final static Logger logger = LoggerFactory.getLogger(ConnectionFactory.class);

    /*public abstract Connection getConnection() throws Exception;*/

    /**
     * Close sql objects.
     *
     * @param obj closeable sql objects
     */
    public static void close(Object ... obj) {
        for(Object o: obj) {
            if(o != null) {
                try {
                    if (o instanceof ResultSet) {
                        ((ResultSet)o).close();
                        logger.trace("[close]: ResultSet is close: Class:{}; Name:{}; SimpleName{};",
                                o.getClass(), o.getClass().getName(), o.getClass().getSimpleName());
                    } else if (o instanceof Statement) {
                        ((Statement)o).clearWarnings();
                        ((Statement)o).close();
                        logger.trace("[close]: Statement is close: Class:{}; Name:{}; SimpleName{};",
                                o.getClass(), o.getClass().getName(), o.getClass().getSimpleName());
                    } else if (o instanceof Connection) {
                        ((Connection)o).clearWarnings();
                        ((Connection)o).close();
                        logger.trace("[close]: Connection is close: Class:{}; Name:{}; SimpleName{};",
                                o.getClass(), o.getClass().getName(), o.getClass().getSimpleName());
                    }
                } catch (Throwable ex) {
                    logger.error("[close]: ERRORR CLOSE SQL CONNECTION: ", ex);
                    System.gc();
                }
            }
        }
    }
}
